<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\orderService;
use app\service\packageService;

use think\Db;
use think\db\Where;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;

class Package extends Common{

    public function carlist(){

		 //根据当前账号查询区域
        $com = $this->pidTokenId();
        $whe=new Where();
        $whe['community_id'] = array('in',implode(',',$com['community_id']));
        //根据账号查询停车场
        $parkinglist = (new orderService())->parkingList($whe);
        $this->assign('parkinglist',$parkinglist);
		 //查询停车场ID
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
        $community_id = $com['community_id'];
        //搜索
        $data = request()->get();
        // dump($data);
        $where=array();
        if (!empty($data)){
            if(!empty($data['parkingNo'])){
                $where[]=['parkingNo','=',$data['parkingNo']];
                //$where['parkingNo'] = $data['parkingNo'];//停车场名称
            }
            if(!empty($data['delivery_status'])){
                $where[]=['delivery_status','=',$data['delivery_status']];
                //$where['delivery_status'] = $data['delivery_status'];
            }
            if(!empty($data['car_number'])){
                $where[]=['car_number','like','%'.$data['car_number'].'%'];
               //$where['car_number'] = array('like','%'.$data['car_number'].'%');//车牌号码//车牌
            }
			
            if(!empty($data['owner_phone'])){
                $where['owner_phone'] = $data['owner_phone'];//车主电话
            }
			if(!empty($data['owner_name'])){
                $where['owner_name'] = $data['owner_name'];//车主电话
            }
            
            $this->assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where=array();
        }
        
        $export = json_encode($where);
        $export = str_replace("\"","|",$export);
        $this->assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //多条件查询地库车位信息
        $carlist = Db::name('car_package')->where('parkingNo', 'in', $parkingNo)->where($where)->order('id desc')->paginate(100, false, [
            'page'  =>  $page,
            'query' =>  $where
        ]);
        $number = Db::name('car_package')->where('parkingNo', 'in', $parkingNo)->where($where)->count();
        $this->assign('number',$number);
		
        $this->assign('carlist',$carlist);
		$this->assign('list',$carlist);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }
        return $this->fetch('carlist');
	}
	
	public function caradd(){
		//根据当前账号查询区域
        $com = $this->pidTokenId();
        $whe=new Where();
        $whe['community_id'] = array('in',implode(',',$com['community_id']));
        $parkinglist = (new orderService())->parkingList($whe);
        $this->assign('parkinglist',$parkinglist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            
			$parkinglotinfo=Db::table("parkinglotinfo")->where("parkingNo",$data["parkingNo"])->find();
			//查询该车辆是否已经添加
			$carinfo=Db::table("car_package")->where("parkingNo",$data["parkingNo"])->where("car_number",$data["car_number"])->find();
			if(!empty($carinfo))
			{
				$this->error('该车辆已经添加',url('caradd'));
			}
			$data["parkingName"]=$parkinglotinfo["parkingName"];
			$data["begin_time"]=strtotime($data["begin_time"]);
			$data["end_time"]=strtotime($data["end_time"]);
            //插入数据到数据库
            $res = Db::table("car_package")->insert($data);
           
            if($res)
			{
                $this->success('车辆添加成功',url('caradd'));
            }else
			{
                $this->error('车辆添加失败',url('caradd'));
            }
        }else{
			 return $this->fetch('');
		}
       
	}
    public function caredit(){
        if(request()->isGet()){
            $id = request()->get('id');
            if(!isset($id) && empty($id)){
                $this->error('该月租车不存在');
            }
            //查询指定ID账单信息
            $info = (new packageService())->packageId($id);
            $this->assign('info',$info);
            return $this->fetch();
        }else{
            $data = request()->post();
            $info = (new packageService())->packageId($data["id"]);
            $data["begin_time"]=strtotime($data["begin_time"]);
            $data["end_time"]=strtotime($data["end_time"]);
            $data["update_at"]=date("Y-m-d H:i:s");
            $result = (new packageService())->packageEdit($data);
            //判断数据是否更新成功
            if($result){
                if($info["delivery_status"]=="1"){
                    $res=(new packageService())->packageEdit(["id"=>$info["id"],"delivery_status"=>"2"]);
                }
                $this->success('添加备注成功',url('carlist'));
            }else{
                $this->error('添加备注失败',url('carlist'));
            }
        }
    }
	public function remarks(){

        if(request()->isGet()){
            $id = request()->get('id');
            if(!isset($id) && empty($id)){
                $this->error('该月租车不存在');
            }
            //查询指定ID账单信息
            $info = (new packageService())->packageId($id);
            $this->assign('info',$info);
            return $this->fetch('remarks');
        }else{
            $data['id'] = request()->post('id');

            $data['remarks'] = request()->post('remarks');
            $data["update_at"]=date("Y-m-d H:i:s");
            $result = (new packageService())->packageEdit($data);

            $info = (new packageService())->packageId($data["id"]);
            //判断数据是否更新成功
            if($result){
                if($info["delivery_status"]=="1"){
                    $res=(new packageService())->packageEdit(["id"=>$info["id"],"delivery_status"=>"2"]);
                }
                $this->success('添加备注成功',url('carlist'));
            }else{
                $this->error('添加备注失败',url('carlist'));
            }
        }
    }
	public function packageIssued(){
	    $id=request()->post("id");
	    $carinfo=Db::table("car_package")->where("id",$id)->find();
	    //查询该车场客户端是否在线
	    $clientinfo=Db::table("client_login")->where("parkingNo",$carinfo["parkingNo"])->where("connect_status","ON")->find();
        if(empty($clientinfo)){
            return json(['error' => "客户端不在线,下发失败"]);
            return "客户端不在线";
        }
        $redis = new \Redis();
        
        $redis->connect('127.0.0.1',6379);
        $redis->auth('zaozao2019@');
        $arr=array($id);
        $data=json_encode($arr);
        
        $res = $redis->publish('car_package',$data);
        if($res){
            return json(['info' => "下发成功"]);
        }else{
            return json(['error' => "下发失败"]);
        }
	}
    public function packageIssuedAll(){
        $id=request()->post("id");
        $idarr = explode(',',$id);
        //查询账单同步的状态
        $parkingNo=Db::table("car_package")->where("id","in",$idarr)->distinct("parkingNo")->field("parkingNo")->select();
        if(count($parkingNo)!="1"){
            return json(['error' => '请选择同一车厂进行操作']);
        }

        //查询该车场客户端是否在线
        $clientinfo=Db::table("client_login")->where("parkingNo",$parkingNo[0]["parkingNo"])->where("connect_status","ON")->find();
        if(empty($clientinfo)){
            return json(['error' => "客户端不在线,下发失败"]);
            return "客户端不在线";
        }
        $redis = new \Redis();

        $redis->connect('127.0.0.1',6379);
        $redis->auth('zaozao2019@');

        $data=json_encode($idarr);

        $res = $redis->publish('car_package',$data);
        if($res){
            return json(['info' => "下发成功"]);
        }else{
            return json(['error' => "下发失败"]);
        }
    }
    public function packageDel(){
        $id=request()->post("id");
        $carinfo=Db::table("car_package")->where("id",$id)->find();
        //新增未下发直接删除
        if(($carinfo["operate_type"]=="1")&&($carinfo["delivery_status"]=="2")){
            $res=Db::table("car_package")->where("id",$id)->delete();
            if($res){
                return json(['info' => "数据删除成功"]);
            }else{
                return json(['error' => "数据删除失败"]);
            }
        }
        //查询该车场客户端是否在线
        $clientinfo=Db::table("client_login")->where("parkingNo",$carinfo["parkingNo"])->where("connect_status","ON")->find();
        if(empty($clientinfo)){
            return json(['error' => "客户端不在线,下发失败"]);
            return "客户端不在线";
        }
        $redis = new \Redis();

        $redis->connect('127.0.0.1',6379);
        $redis->auth('zaozao2019@');
        $arr=array($id);
        $data=json_encode($arr);

        $res = $redis->publish('car_package',$data);
        if($res){
            $carinfo=Db::table("car_package")->where("id",$id)->update(["operate_type"=>"3"]);
            return json(['info' => "下发成功"]);
        }else{
            return json(['error' => "下发失败"]);
        }
    }
	
	public function packagedump(){
		//获取账单数据
        $export = request()->param('exportid');
		
        $export = str_replace("|","\"",$export);
        //根据当前账号查询区域
        $com = (new Common())->pidTokenId();
        $whe=new Where();
        $whe['community_id'] = array('in',implode(',',$com['community_id']));
        //根据账号查询停车场
        $parkinglist = (new orderService())->parkingList($whe);
		 //查询停车场ID
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
		
        $where = json_decode($export,true);
		
		//多条件查询储值车充值记录信息

        $carlist = Db::name('car_package')->where('parkingNo', 'in', $parkingNo)->where($where)->order('id desc')->select();
		$num=Db::name('car_package')->where('parkingNo', 'in', $parkingNo)->where($where)->count();
		if($num=="0"){
			return  "无数据";
		}
		//引入PHPExcel类
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        //设置表头
        $objSheet->setTitle('月租车');
        $objSheet->setCellValue('A1', '停车场编号')
            ->setCellValue('B1', '停车场名称')
            ->setCellValue('C1', '车牌号')
            ->setCellValue('D1', '姓名')
            ->setCellValue('E1', '电话')
            ->setCellValue('F1', '车位价格')
            ->setCellValue('G1', '开始时间')
            ->setCellValue('H1', '结束时间')
            ->setCellValue('I1', '地址')
            ->setCellValue('J1', '备注');
        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
		for ($i = 2; $i <= $num+1; $i++) {
            $objSheet->setCellValue('A' . $i, $carlist[$i-2]["parkingNo"]);
            $objSheet->setCellValue('B' . $i, $carlist[$i-2]["parkingName"]);
            $objSheet->setCellValue('C' . $i, $carlist[$i-2]["car_number"]);
            $objSheet->setCellValue('D' . $i, $carlist[$i-2]["owner_name"]);
            $objSheet->setCellValue('E' . $i, $carlist[$i-2]["owner_phone"]);

            $objSheet->setCellValue('F' . $i, $carlist[$i-2]["price"]);
            $objSheet->setCellValue('G' . $i, date('Y-m-d H:i:s',$carlist[$i-2]["begin_time"]));
            $objSheet->setCellValue('H' . $i, date('Y-m-d H:i:s',$carlist[$i-2]["end_time"]));
            $objSheet->setCellValue('I' . $i, $carlist[$i-2]["address"]);
            $objSheet->setCellValue('J' . $i, $carlist[$i-2]["remarks"]);
        }
        $this->downloadExcel($newExcel, "月租车", 'Xls'); //表示在$path路径下面生成demo.xlsx文件
	}

	//月租车导入
	public function packageExcel(){
        if(request()->isPost()){

            //通过注入的request对象获取上传的文件
            $file  = request()->file('myfile');
            //对文件大小和格式进行验证
            $info = $file->validate(['size'=>5*1024*1024,'ext'=>'xls'])->move( 'uploads/excel');
            if(!$info){
                $this->error($file->getError());
            }
            //声明读取的文件格式
            $objReader = IOFactory::createReader('Xls');

            //加载excel文件
            $objPHPExcel = $objReader->load(BASE_PATH.'uploads/excel/'.$info->getSaveName());
            //读取默认工作表
            $worksheet = $objPHPExcel->getSheet(0);
            //取得一共有多少行
            $allRow = $worksheet->getHighestRow();

            $dataall = [];
            for ($i = 2; $i <= $allRow; $i++)
            {
                $data['parkingNo'] = $objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue();
                $data['parkingName'] = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
                $data['car_number'] = $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
                $data['owner_name'] = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue();
                $data['owner_phone'] = $objPHPExcel->getActiveSheet()->getCell('E'.$i)->getValue();

                $data['price'] = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();
                $data['begin_time'] = strtotime($objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue());
                //$data['begin_time2'] = $objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue();
                $data['end_time'] = strtotime($objPHPExcel->getActiveSheet()->getCell('H'.$i)->getValue());
                //$data['end_time2'] = $objPHPExcel->getActiveSheet()->getCell('H'.$i)->getValue();
                $data['address'] = strtotime($objPHPExcel->getActiveSheet()->getCell('I'.$i)->getValue());
                $data['remarks'] = $objPHPExcel->getActiveSheet()->getCell('J'.$i)->getValue();


                //插入数据库
                //查询车牌是否重复
                $carinfo=Db::table("car_package")->where("parkingNo",$data["parkingNo"])->where("car_number",$data["car_number"])->find();
                if(!empty($carinfo)){
                    return "第".$i."行车牌重复";
                }
                $dataall[]=$data;
            }
            //insertAll
            //echo "<pre>";
            //var_dump($dataall);die;
            $res=Db::table("car_package")->insertAll($dataall);
            if($res){
                return "数据导入成功";
            }else{
                return "数据导入失败";
            }
        }else{
            return $this->fetch("carexcel");
        }
    }
	

	

	
	public function orderinfo()
	{
		$com = $this->pidTokenId();
		$id=request()->get("id");
		$carinfo=Db::table("car_owner_welfare")->where("id",$id)->find();
		$data = request()->get();
		//var_dump($data);
        if (!empty($data)){
			if(!empty($data['in_year'])){
                $where['in_year'] = $data['in_year'];
            }else{
                $where['in_year'] = "";
            }
            if(!empty($data['in_month'])){
                $where['in_month'] = $data['in_month'];
            }else{
                $where['in_month'] = "";
            }
            $this->assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where=array();
        }
		$where["out_parking_id"]=$carinfo["out_parking_id"];
		$where["car_number"]=$carinfo["car_number"];
		$where["pstatus"]="1";
		//var_dump($where);
		$page = request()->has('page') ? request()->get('page') : 1;
		//查询该车的停车记录
		$orderwelfare=Db::table("car_order_welfare")
							->where($where)
							->order("id desc")
							->paginate(100, false, [
								'page'  =>  $page,
								'query' =>  $where
							]);
		$feetime=Db::table("car_order_welfare")
							->where($where)
							->sum("fee_duration");
		$this->assign("feetime",$feetime);
		$this->assign("orderwelfare",$orderwelfare);
		foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }
        $this->assign("id",$id);
		return $this->fetch();
	}
	

	
	
	function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }	
}